from __future__ import annotations

import re

from papis.downloaders import Downloader


class DocumentDownloader(Downloader):
    """Retrieve documents from remote PDF, EPUB or other files"""

    def __init__(self, url: str) -> None:
        super().__init__(url, name="get", priority=0)

    @classmethod
    def match(cls, url: str) -> Downloader | None:
        """
        >>> DocumentDownloader.match('https://wha2341!@#!@$%!@#file.pdf') is None  # spell: disable
        False
        >>> DocumentDownloader.match('https://whateverpt?is?therefile.epub') is None
        False
        >>> DocumentDownloader.match('https://whatever?path?is?therefile') is None
        True
        """  # noqa: E501
        endings = "pdf|djvu|epub|mobi|jpg|png|md"
        m = re.match(fr"^http.*\.({endings})$", url, re.IGNORECASE)
        if m:
            d = DocumentDownloader(url)

            extension = m.group(1)
            d.expected_document_extensions = (extension,)
            d.logger.info("Expecting a document of type '%s'.", extension)

            return d
        else:
            return None

    def get_document_url(self) -> str | None:
        return self.uri
